var orderStatus = "";
//订单列表实例
var $table = $("#order_list_table");
//当前产品线
var sourceType;

var modalOrderId;
var modalIsLogistics;

$(function () {
    var userName=getvl("userName");
    $("#searchUsername").val(userName)
    initOrdersTable($table);
});

/*//更换产品线
$("#groupType").change(function () {
    var temp = $("#groupType").val();
    sourceType = temp;
    $table.bootstrapTable('refresh');
});

//更换筛选订单状态
$("#orderStatus").change(function () {
    var temp = $("#orderStatus").val();
    orderStatus = temp;
    $table.bootstrapTable('refresh');
});*/


// 重置搜索
function resetting() {
    // 重置input
    $("#searchForm input").val("");
    //重置select
    $("#searchForm select").each(function (i, n) {
        // $(this).find('option:first').prop("selected",true);
        $(this).prop('selectedIndex', 0);
        ;
    });
    $("#searchForm select").change();
    $table.bootstrapTable('refresh');
}

var columns = [
   /* {
        checkbox: true,
    },*/ {
        title: "序号",
        align: "center",
        valign: "middle",
        width: "50px",
        formatter: function (value, row, index) {
            return (index + 1);
        }
    }, {
        field: "id",
        title: "订单ID",
        halign: "center",
        valign: "middle",
        align: "center",
        width: "80px"
    }, {
        field: "orderNumber",
        title: "订单编号",
        valign: "middle",
        halign: "center",
        sortable: true
    }, {
        field: "orderGoodsList",
        title: "订单商品",
        width: "400px",
        halign: "center",
        align: "center",
        sortable: true,
        formatter: function (value, row, index) {
            var liHtml = "";
            for (var ogItem of value) {
                if (null != ogItem.goods) {
                    var goodsUrl = ogItem.goods.goodsUrl;
                    var goodsName = ogItem.goods.goodsName;
                    var sku = ogItem.sku;
                    var valuesStr = "";
                    if (sku.ifUniformSpec == 1)
                        valuesStr = ogItem.sku.valuesStr;
                    if (sku.ifUniformSpec == 0)
                        valuesStr = "统一规格";
                    var skuCount = ogItem.skuCount;
                    liHtml += "    <tr class=\"content-row\">\n" +
                        "<td><img style=\"width: 50px;height: 50px;\" src=\"" + goodsUrl + "\"></td>" +
                        "                                    <td>\n" +
                        "                                        <div style=\"width: 200px;\"><a href=\"javascript:;\">" +
                        goodsName +
                        "</a><br>" +
                        // 自有库存小于某数值时标红
                        "自有库存：(" + (sku.inventory < 15 ? "<span style='color: red'>" : "<span>") + sku.inventory + "</span>)" +
                        "</div>\n" +
                        "                                    </td>\n" +
                        "                                    <td>" +
                        valuesStr +
                        "</td>\n" +
                        "                                    <td>" +
                        skuCount + "件" +
                        "</td>\n" +
                        "                                </tr>";

                } else {
                    liHtml += "商品已被删除";
                }
                var htmlStr =
                    "                            <table class=\"table order-list\">\n" +
                    "                                <tbody id=\"modalGoodsList\" class=\"widget-list-item\">\n" +
                    liHtml +
                    "                                </tbody>\n" +
                    "                            </table>";
            }
            return htmlStr;
        }

    }, {
        field: "totalPrice",
        title: "订单总价",
        align: "center",
        valign: "middle",
        halign: "center",
        width: "50px",
        sortable: true,
        formatter: function (value, row, index) {
            var sumPrice = row.totalPrice + row.couponVal - row.deliveryMoney;
            //如果原来是整数等就取原来的整数，小数过来的保留两位小数
            if (sumPrice.toString().split(".").length > 1) {
                sumPrice = sumPrice.toFixed(2)
            }
            return sumPrice;
        }
    }, {
        field: "deliveryMoney",
        title: "配送费",
        align: "center",
        valign: "middle",
        halign: "center",
        sortable: true
    }, {
        field: "couponVal",
        title: "优惠券额",
        align: "center",
        valign: "middle",
        halign: "center",
        sortable: true
    }, {
        field: "totalPrice",
        title: "应付金额",
        align: "center",
        valign: "middle",
        halign: "center",
        width: "50px",
        sortable: true

    }, {
        field: "cashPayPrice",
        title: "现金实付",
        align: "center",
        valign: "middle",
        halign: "center",
        width: "50px",
        sortable: true,
        formatter: function (value, row, index) {
            if (row.payType == "3" || row.payType == "4") {
                return value;
            } else return "";
        }
    }, {
        field: "totalPrice",
        title: "余额支付",
        align: "center",
        valign: "middle",
        halign: "center",
        width: "50px",
        sortable: true,
        formatter: function (value, row, index) {
            if (row.payDatetime != null) {
                if (row.payType == "3" || row.payType == "4") {
                    value = value - row.cashPayPrice;
                    if (value.toString().split(".").length > 1) {
                        value = value.toFixed(2)
                    }
                }
                return value;
            } else return "";
        }
    }, {
        field: "sourceType",
        title: "订单产品线",
        halign: "center",
        valign: "middle",
        width: "80px",
        sortable: true,
        formatter: function (value, row, index) {
            return convertSourceType(value);
        }
    }, {
        field: "muser",
        title: "买家姓名",
        halign: "center",
        valign: "middle",
        width: "80px",
        sortable: true,
        formatter: function (value, row, index) {
            var muserName = value.userName;
            return muserName;
        }
    }, {
        field: "payType",
        title: "支付类型",
        align: "center",
        valign: "middle",
        halign: "center",
        sortable: true,
        formatter: function (value, row, index) {
            return convertPayType(value);
        }
    }, {
        field: "logisticsNumber",
        title: "物流编号",
        align: "center",
        valign: "middle",
        width: "70px",
        halign: "center",
        sortable: true
    }, {
        field: "gmtDatetime",
        title: "下单时间",
        align: "center",
        valign: "middle",
        halign: "center",
        sortable: true
    }, {
        field: "leavingMessage",
        title: "买家留言",
        halign: "center",
        sortable: true
    }, {
        field: "orderStatus",
        title: "订单状态",
        align: "center",
        valign: "middle",
        width: "70px",
        halign: "center",
        sortable: true,
        formatter: function (value, row, index) {
            return convertOrderStatus(value, row.orderType);
        }
    }, {
        title: "操作",
        halign: "center",
        valign: "middle",
        sortable: true,
        formatter: function (value, row, index) {
            var optHtml = "";
            //当前2 待发货 可选发货操作
            if (row.orderStatus == 2)
            // optHtml += "<a class=\"btn btn-primary btn-xs\" href=\"javascript:;\" onclick=\"shippingBatch(" + row.id + ")\"> 发货</a>\n";
                optHtml += "<a class=\"btn btn-primary btn-xs\" href=\"javascript:;\" onclick=\"openShipModal(" + row.id + ")\" data-toggle=\"modal\" data-target=\"#shippingModal\"> 发货</a>\n";
            /*    //当前除了4 已完成 可选关闭操作
                if (row.orderStatus != 4 && row.orderStatus != 5&& row.orderStatus != 6&& row.orderStatus != 7&& row.orderStatus != 8&& row.orderStatus != 9)
                    optHtml += "<a class=\"btn btn-danger btn-xs\" href=\"javascript:;\" onclick=\"closeOrderBatch(" + row.id + ")\"> 关闭</a>\n";
    */
            optHtml += "<a class=\"btn btn-primary btn-xs\" href=\"order_detail.html?id=" + row.id + "\"> 详细</a>\n";
            return optHtml;
        }
    }];

//搜索
function dosearch() {
    $table.bootstrapTable('refresh');
}

var queryParams = function (params) {
    console.log("params:", params);
    var search = params.search == undefined ? "" : params.search;
    //封装page，搜索筛选参数放到condition中
    var param = {
        offset: params.offset,
        current: params.offset / params.limit + 1,//bootstrap-table分页参数offset从0开始，计算的后端当前页参数current=(offset/limit+1)，
        size: params.limit,
        condition: {
            searchText: search,
            orderStatus: $("#orderStatus").val(),
            sourceType: $("#groupType").val(),
            orderType: $("#orderType").val(),
            userName: $("#searchUsername").val(),
            goodsName: $("#searchGoodsName").val()
        }
    };

    return param;
}


//初始化表格 tableins:表格实例 ,
function initOrdersTable(tableins) {
    tableins.bootstrapTable({
        columns: columns,
        method: "post",
        url: urlcore + "/api/orders/getAllOrdersByCondition",
        dataType: "json",
        queryParams: function (params) {
            return queryParams(params);
        },
        //返回数据预处理
        responseHandler: function (cbdata) {
            console.log(cbdata);
            if (null != cbdata.data && null != cbdata.data.records) {
                var records = cbdata.data.records;
                console.log(records);
                var res = {
                    //如果采用server端分页，必须有rows和total这两部分数据
                    "rows": records,
                    "total": cbdata.data.total
                };
                return res;
            } else return {"rows": [], "total": 0};
        },
        cache: false,
        uniqueId: "id",
        // toolbar: '#OrderListToolbar',//自定义工具栏，不同表格工具栏不同，一个jQuery 选择器，指明自定义的toolbar 例如:#toolbar, .toolbar.
        pagination: true,//启用分页条
        sidePagination: "server",//分页方式client或server
        // pageNumber: 1,
        pageSize: 16,//每页大小
        pageList: [16, 32, 48, 64],//可以选择每页大小
        showRefresh: true,//显示刷新
        sortable: true,//是否启用排序
        // clickToSelect: true,//设置true 将在点击行时，自动选择rediobox 和 checkbox
        search: true,//默认为客户端搜索，服务器端接收params中的searchText后可以做服务器端搜索
        // searchText:"",//初始搜索文本
    });
}


//打开发货模态框，填充数据
function openShipModal(id) {
    modalOrderId = id;
    //要先设置bootstrap-table中的uniqueId: "id",得到该行原始数据
    var originalOrderData = $table.bootstrapTable('getRowByUniqueId', id);
    var modalReceiverInfo = originalOrderData;

    var modalLeavingMsg = originalOrderData.leavingMessage;

    var receiverInfoText = getReceiverInfoText(modalReceiverInfo);
    $("#modalReceiverInfo").text(receiverInfoText);
    $("#modalLeavingMsg").text(modalLeavingMsg);

    var orderGoodsList = originalOrderData.orderGoodsList;
    assignModalGoods(orderGoodsList);

}

//模态框商品信息赋值
function assignModalGoods(orderGoodsList) {
    var liHtml = "";
    for (var ogItem of orderGoodsList) {
        var goodsUrl = ogItem.goods.goodsUrl;
        var goodsName = ogItem.goods.goodsName;
        var sku = ogItem.sku;
        var valuesStr = "";
        if (sku.ifUniformSpec == 1)
            valuesStr = ogItem.sku.valuesStr;
        if (sku.ifUniformSpec == 0)
            valuesStr = "统一规格";
        var skuCount = ogItem.skuCount;

        liHtml += "    <tr class=\"content-row\">\n" +
            "<td><img style=\"width: 50px;height: 50px;\" src=\"" + goodsUrl + "\"></td>" +
            "                                    <td>\n" +
            "                                        <div style=\"width: 200px;\"><a href=\"javascript:;\">" +
            goodsName +
            "</a></div>\n" +
            "                                    </td>\n" +
            "                                    <td>" +
            valuesStr +
            "</td>\n" +
            "                                    <td>" +
            skuCount +
            "</td>\n" +
            "                                    <td colspan=\"2\"\n" +
            "                                        style=\"padding: 0px;\">\n" +
            "                                        <table class=\"table table-delivery\" style=\"margin: 0px;\">\n" +
            "                                            <colgroup>\n" +
            "                                                <col width=\"50%\">\n" +
            "                                                <col width=\"50%\">\n" +
            "                                            </colgroup>\n" +
            "                                            <tbody class=\"widget-list-item\"></tbody>\n" +
            "                                        </table>\n" +
            "                                    </td>\n" +
            "                                </tr>";
    }
    $("#modalGoodsList").html(liHtml);
}


//获取modal收货信息文本
function getReceiverInfoText(receiverInfo) {
    var receiverName = receiverInfo.receiverName;
    var receiverPhone = receiverInfo.receiverPhone;

    /*    var receiProvince = receiverInfo.province;
        var city = receiverInfo.city;
        var area = receiverInfo.area;
        var addressDetail = receiverInfo.addressDetail;*/
    var receiverAddress = receiverInfo.receiverAddress + "," + receiverName + "," + receiverPhone;
    return receiverAddress;
}

//无需物流和需要物流，0 为无需物流 1 为需要物流
$(".deliveryRadio").change(function () {
    modalIsLogistics = $("input[name='deliveryRadio']:checked").val();
    if (modalIsLogistics == "0")
        $("#isLogisticsShowDiv").hide();
    if (modalIsLogistics == "1")
        $("#isLogisticsShowDiv").show();
});

// 修改订单，发货,optionTag 0 发货
function shipping(orderId) {
    var isLogistics = $('input[type="radio"][name="deliveryRadio"]:checked').val();
    var merchantRemarks = $("#merchantRemarks").val();
    console.log("isLogistics", isLogistics);
    if (isLogistics == undefined) {
        alert("请先选择是否需要物流");
        return;
    }

    var uptModel = new Object();
    if (isLogistics == 0) {
        uptModel = {
            id: modalOrderId,
            isLogistics: isLogistics,
            merchantRemarks: merchantRemarks,
            orderStatus: 3
        };
    }
    if (isLogistics == 1) {
        var logisticsNumber = $("#modalDeliveryNum").val();
        if (logisticsNumber == "") {
            alert("请输入快递单号")
            return;
        }
        //快递公司代号
        var logiCom = $("#modalDeliveryCom").val();
        uptModel = {
            id: modalOrderId,
            isLogistics: isLogistics,
            logiCom: logiCom,
            logisticsNumber: logisticsNumber,
            orderStatus: 3
        };
    }
    $.ajax({
        type: "POST",
        url: urlcore + "/api/orders/update",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(uptModel),
        success: function (data) {
            alert("订单发货成功！");
            console.log("batchskudata", data);
            $table.bootstrapTable("refresh");
            initModal();
        },
        error: function () {

        }
    });
}

//取消发货
function cancelShipping() {
    initModal();
}

//初始化模态框
function initModal() {
    $("#isLogisticsShowDiv").show();
    $("input[type='radio'][name='deliveryRadio'][value='1']").prop("checked", "checked");
    $("#modalGoodsList").html("");
    $("#modalDeliveryNum").val("");
    $("#merchantRemarks").val("");
    modalOrderId = "";
    modalIsLogistics = "";
}

// 修改订单，关闭订单
function closeOrderBatch(orderId) {
    confirm("确认关闭订单吗？", function (callback) {
        if (callback) {
            closeOrder();
        }
    });

    //关闭订单   8为商家取消
    function closeOrder() {
        var uptModelList = [];
        if (orderId != undefined) {
            uptModelList.push({
                id: orderId,
                orderStatus: 8
            });
        } else {
            var selection = $table.bootstrapTable('getSelections');
            if (selection.length == 0) {
                alert("请先选择订单");
                return;
            }
            for (var item of selection) {
                uptModelList.push({
                    id: item.id,
                    orderStatus: 8
                });
            }
        }


        $.ajax({
            type: "POST",
            url: urlcore + "/api/orders/uptOrderBatch",
            dataType: "json",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(uptModelList),
            success: function (data) {
                alert("订单关闭成功！");
                console.log("batchskudata", data);
                $table.bootstrapTable("refresh");
            },
            error: function () {

            }
        });
    }

}


//转化产品线
function convertSourceType(value) {
    var result;
    if (value == 0) {
        result = "蜜哆哆";
    } else if (value == 1) {
        result = "蜜雅阁";
    }
    return result;
}

//转化支付方式
function convertPayType(value) {
    var result;
    if (value == 1) {
        result = "哆币";
    } else if (value == 2) {
        result = "雅币";
    } else if (value == 3) {
        result = "支付宝";
    } else if (value == 4) {
        result = "微信";
    }
    return result;
}

//转化订单状态 已完成和待评价都是交易完成 6-9都是交易关闭
function convertOrderStatus(value, orderType) {
    var result;
    if (value == null || value == undefined)
        return "";
    if (value == 1) {
        result = "待付款";
    } else if (value == 2) {
        result = "未发货";
    } else if (value == 3) {
        result = "已发货";
    } else if (value == 4) {
        result = "已完成";
    } else if (value == 5) {
        result = "待评价";
    } else if (value == 6) {
        result = "自动取消";
    } else if (value == 7) {
        result = "买家取消";
    } else if (value == 8) {
        result = "商家取消";
    } else if (value == 9) {
        if (orderType == 0) {
            result = "维权完成已退款";
        } else if (orderType == 1) {
            result = "拼团失败已退款"
        }
    } else if (value == 10) {
        result = "退款中";
    }
    return result;
}